package sync
{
	import actions.WBAction;
	
	import model.WBObject;
	
	import mx.collections.ArrayCollection;

	public class ObjectSynchronizer
	{
		private var _object:WBObject;
		// a queue of future actions waiting to be processed
		private var _actionQueue:Array;
		//a list of actions that have already been processed
		private var _historyList:Array;
		private var _isInSyncProgress:Boolean;
		
		public function ObjectSynchronizer()
		{
			_actionQueue = new ArrayCollection();
			_historyList = new ArrayCollection();
			_isInSyncProgress = false;
		}

		public function get object():WBObject
		{
			return _object;
		}

		public function set object(value:WBObject):void
		{
			_object = value;
		}
		
		public function addAction(action:WBAction):void
		{
			_actionQueue.push(action);
			beginSync();
		}
		
		private function commitObjectProperties():void
		{
			
		}
		
		private function beginSync():void
		{
			if(!_isInSyncProgress)
			{
				if(_actionQueue.length > 0)
				{
					//take first in queue
					var currentAction:WBAction = _actionQueue.shift();
					if(_historyList.length == 0)
					{
						object.redo(currentAction);
						commitObjectProperties();
						_historyList.push(currentAction);
					}
					else
					{
						var i:int = 0;
						for (i = 0; i < _historyList.length; i++)
						{
							if((_historyList[i] as WBAction).timeStamp.time <= currentAction) 
							{
								i++;
							}
							else
							{
								// insert action on i-th place
								var before:Array = _historyList.splice(i, 0, currentAction);
								var j:int = 0; 
							}
						}
					}
				}
			}
		}

	}
}